{% extends "admin/layout.html" %}

{% block title %}帖子管理 - 墨韵管理系统{% endblock %}

{% block admin_title %}帖子管理{% endblock %}

{% block admin_content %}
<div class="card ink-card mb-4">
    <div class="card-header ink-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">帖子列表</h5>
        <div class="d-flex align-items-center">
            <div class="dropdown me-2">
                <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" id="statusDropdown" data-bs-toggle="dropdown">
                    状态: {{ status if status != 'all' else '全部' }}
                </button>
                <ul class="dropdown-menu" aria-labelledby="statusDropdown">
                    <li><a class="dropdown-item {{ 'active' if status == 'all' else '' }}" href="{{ url_for('admin_posts', status='all') }}">全部</a></li>
                    <li><a class="dropdown-item {{ 'active' if status == 'pending' else '' }}" href="{{ url_for('admin_posts', status='pending') }}">
                        待审核 {% if pending_count %}<span class="badge bg-danger">{{ pending_count }}</span>{% endif %}
                    </a></li>
                    <li><a class="dropdown-item {{ 'active' if status == 'approved' else '' }}" href="{{ url_for('admin_posts', status='approved') }}">已批准</a></li>
                    <li><a class="dropdown-item {{ 'active' if status == 'rejected' else '' }}" href="{{ url_for('admin_posts', status='rejected') }}">已拒绝</a></li>
                </ul>
            </div>
            {% if status == 'pending' %}
            <small>
                <a href="#" class="text-muted" data-bs-toggle="collapse" data-bs-target="#quickApprovalHelp">
                    <i class="fas fa-question-circle"></i> 快速审核操作
                </a>
            </small>
            {% endif %}
        </div>
    </div>
    
    {% if status == 'pending' %}
    <div class="collapse" id="quickApprovalHelp">
        <div class="card-body bg-light">
            <h6><i class="fas fa-info-circle"></i> 快速审核</h6>
            <p class="mb-0">若模态框提交有问题，您可以直接通过下方操作栏直接进行审核操作。</p>
        </div>
    </div>
    {% endif %}
    
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="bg-light">
                    <tr>
                        <th>ID</th>
                        <th>标题</th>
                        <th>作者</th>
                        <th>所属圈子</th>
                        <th>发布时间</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for post in posts.items %}
                    <tr>
                        <td>{{ post.id }}</td>
                        <td>
                            <a href="{{ url_for('view_post', post_id=post.id) }}" target="_blank" class="text-decoration-none">
                                {{ post.title }}
                            </a>
                        </td>
                        <td>{{ post.author.username }}</td>
                        <td>
                            {% if post.circle %}
                            <a href="{{ url_for('circle_detail', circle_id=post.circle.id) }}" target="_blank" class="badge bg-info text-decoration-none">
                                {{ post.circle.name }}
                            </a>
                            {% else %}
                            <span class="badge bg-secondary">公共区</span>
                            {% endif %}
                        </td>
                        <td>{{ post.created_at.strftime('%Y-%m-%d %H:%M') }}</td>
                        <td>
                            {% if post.status == 'pending' %}
                            <span class="badge bg-warning">待审核</span>
                            {% elif post.status == 'approved' %}
                            <span class="badge bg-success">已批准</span>
                            {% elif post.status == 'rejected' %}
                            <span class="badge bg-danger">已拒绝</span>
                            {% endif %}
                        </td>
                        <td>
                            <div class="btn-group">
                                <a href="{{ url_for('view_post', post_id=post.id) }}" class="btn btn-sm btn-outline-primary" target="_blank">
                                    <i class="fas fa-eye"></i>
                                </a>
                                {% if post.status == 'pending' %}
                                <button type="button" class="btn btn-sm btn-outline-success approve-direct-btn" data-post-id="{{ post.id }}" data-post-title="{{ post.title }}">
                                    <i class="fas fa-check"></i>
                                </button>
                                <button type="button" class="btn btn-sm btn-outline-danger reject-direct-btn" data-post-id="{{ post.id }}" data-post-title="{{ post.title }}">
                                    <i class="fas fa-times"></i>
                                </button>
                                
                                <!-- 直接操作按钮 -->
                                <form action="{{ url_for('approve_post', post_id=post.id) }}" method="post" class="d-inline direct-approve-form">
                                    <button type="submit" class="btn btn-sm btn-success" title="直接通过">
                                        <i class="fas fa-check-double"></i>
                                    </button>
                                </form>
                                {% endif %}
                            </div>
                        </td>
                    </tr>
                    {% else %}
                    <tr>
                        <td colspan="7" class="text-center py-4">暂无帖子</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
    <div class="card-footer">
        <!-- 分页 -->
        {% if posts.pages > 1 %}
        <nav>
            <ul class="pagination justify-content-center mb-0">
                <li class="page-item {% if not posts.has_prev %}disabled{% endif %}">
                    <a class="page-link" href="{{ url_for('admin_posts', page=posts.prev_num, status=status) }}">上一页</a>
                </li>
                {% for page_num in posts.iter_pages(left_edge=1, right_edge=1, left_current=2, right_current=2) %}
                    {% if page_num %}
                        <li class="page-item {% if page_num == posts.page %}active{% endif %}">
                            <a class="page-link" href="{{ url_for('admin_posts', page=page_num, status=status) }}">{{ page_num }}</a>
                        </li>
                    {% else %}
                        <li class="page-item disabled">
                            <span class="page-link">...</span>
                        </li>
                    {% endif %}
                {% endfor %}
                <li class="page-item {% if not posts.has_next %}disabled{% endif %}">
                    <a class="page-link" href="{{ url_for('admin_posts', page=posts.next_num, status=status) }}">下一页</a>
                </li>
            </ul>
        </nav>
        {% endif %}
    </div>
</div>
{% endblock %}

{% block admin_scripts %}
<!-- 服务器端渲染好的数据，以data属性传递给JavaScript -->
<div id="jinja-data" 
     data-approve-url="{{ url_for('approve_post', post_id=0) }}"
     data-reject-url="{{ url_for('reject_post', post_id=0) }}"
     {% if csrf_token %}
     data-csrf-token="{{ csrf_token }}"
     {% endif %}
     style="display:none;"></div>

<!-- 纯JavaScript代码，不包含任何Jinja2语法 -->
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 从DOM中获取数据属性
        var dataElement = document.getElementById('jinja-data');
        var approvePostUrl = dataElement.getAttribute('data-approve-url');
        var rejectPostUrl = dataElement.getAttribute('data-reject-url');
        var csrfToken = dataElement.getAttribute('data-csrf-token');
        
        // 设置jQuery的AJAX全局设置，添加CSRF保护
        if (csrfToken) {
            $.ajaxSetup({
                beforeSend: function(xhr, settings) {
                    if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                        xhr.setRequestHeader("X-CSRFToken", csrfToken);
                    }
                }
            });
        }
        
        // 直接批准帖子按钮
        document.querySelectorAll('.approve-direct-btn').forEach(function(btn) {
            btn.addEventListener('click', function() {
                const postId = this.getAttribute('data-post-id');
                const postTitle = this.getAttribute('data-post-title');
                
                if (confirm(`您确定要批准《${postTitle}》这篇帖子吗？批准后，该帖子将对所有用户可见。`)) {
                    // 禁用按钮防止重复提交
                    this.disabled = true;
                    this.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>';
                    
                    // 使用原生JavaScript发送POST请求
                    const xhr = new XMLHttpRequest();
                    xhr.open('POST', approvePostUrl.replace('0', postId), true);
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    if (csrfToken) {
                        xhr.setRequestHeader('X-CSRFToken', csrfToken);
                    }
                    
                    xhr.onload = function() {
                        if (xhr.status === 200) {
                            window.location.reload();
                        } else {
                            alert('批准失败，请重试');
                            btn.disabled = false;
                            btn.innerHTML = '<i class="fas fa-check"></i>';
                        }
                    };
                    
                    xhr.onerror = function() {
                        alert('批准失败，请重试');
                        btn.disabled = false;
                        btn.innerHTML = '<i class="fas fa-check"></i>';
                    };
                    
                    xhr.send();
                }
            });
        });
        
        // 直接拒绝帖子按钮
        document.querySelectorAll('.reject-direct-btn').forEach(function(btn) {
            btn.addEventListener('click', function() {
                const postId = this.getAttribute('data-post-id');
                const postTitle = this.getAttribute('data-post-title');
                
                const reason = prompt(`您确定要拒绝《${postTitle}》这篇帖子吗？\n\n请输入拒绝原因：`);
                if (reason !== null) {
                    if (reason.trim() === '') {
                        alert('请输入拒绝原因');
                        return;
                    }
                    
                    // 禁用按钮防止重复提交
                    this.disabled = true;
                    this.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>';
                    
                    // 使用原生JavaScript发送POST请求
                    const xhr = new XMLHttpRequest();
                    xhr.open('POST', rejectPostUrl.replace('0', postId), true);
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    if (csrfToken) {
                        xhr.setRequestHeader('X-CSRFToken', csrfToken);
                    }
                    
                    xhr.onload = function() {
                        if (xhr.status === 200) {
                            window.location.reload();
                        } else {
                            alert('拒绝失败，请重试');
                            btn.disabled = false;
                            btn.innerHTML = '<i class="fas fa-times"></i>';
                        }
                    };
                    
                    xhr.onerror = function() {
                        alert('拒绝失败，请重试');
                        btn.disabled = false;
                        btn.innerHTML = '<i class="fas fa-times"></i>';
                    };
                    
                    xhr.send('reason=' + encodeURIComponent(reason));
                }
            });
        });
    });
</script>
{% endblock %} 